const PENDING = 'PENDING',
      FULFILLED = 'FULFILLED',
      REJECTED = 'REJECTED';
class MyPromise {
  constructor (executor) {
    this.status = PENDING;
    this.value = undefined;
    this.reason = undefined;
    this.onFulFilledCallbacks = [];
    this.onRejectedCallbacks = [];

    const resolve = (value) => {
      if (this.status === PENDING) {
        this.status = FULFILLED;
        this.value = value;
        console.log('123');
        this.onFulFilledCallbacks.forEach(fn => fn()) // fn = () => {onFulfilled(this.value);}()
      }
    }

    const reject = (reason) =>{
      if (this.status === PENDING) {
        this.status = REJECTED;
        this.reason = reason;

        this.onRejectedCallbacks.forEach(fn => fn())
      }
    }
    
    // if (this.status === PENDING) {
    //   this.status
    // }

    try {
      executor(resolve, reject); // 执行器
    } catch (e) {
      reject (e);
    }
  } // 构造器

  then (onFulfilled, onRejected) {
    if (this.status === FULFILLED) {
      onFulfilled(this.value);
    }

    if (this.status === REJECTED) {
      console.log('999');
      onRejected(this.reason);
    }
    
    if (this.status === PENDING) {
      // 订阅
      this.onFulFilledCallbacks.push(() => {
        onFulfilled(this.value);
      })

      this.onRejectedCallbacks.push(() => {
        onRejected(this.reason);
      })
    }
  }
}

// catch 在promise的源码层面上就是一个then，catch也是遵循then的运行原则

module.exports = MyPromise;